package strings;

/**
 * @author pengfei.hpf
 * @date 2020/3/6
 * @verdion 1.0.0
 */
public class ValidTicTacToe {
    public boolean validTicTacToe(String[] board) {
        if(board == null || board.length !=3){
            return false;
        }
        char[][] chars = new char[3][3];
        for(int i = 0; i < 3; i ++){
            if(board[i].length() != 3){
                return false;
            }
            chars[i] = board[i].toCharArray();
        }
        return isValid(chars);
    }

    private boolean isValid(char[][] board){
        int[] count = new int[2];
        boolean xWin = false;
        boolean yWin = false;
        for(int i = 0; i < 3; i++){
            int[] row = new int[2];
            for(int j = 0; j < 3; j++){
                if(board[i][j] == 'X'){
                    count[0] ++;
                    row[0]++;
                } else if(board[i][j] == 'O'){
                    count[1]++;
                    row[1] ++;
                }
            }
            if(row[0] == 3){
                xWin = true;
            }
            if(row[1] == 3){
                yWin = true;
            }
        }
        if(count[0] != count[1] && count[0] != count[1] + 1){
            return false;
        }
        for(int i = 0; i < 3; i++){
            int[] col = new int[2];
            for(int j = 0; j < 3; j++){
                if(board[j][i] == 'X'){
                    col[0]++;
                } else if(board[j][i] == 'O'){
                    col[1] ++;
                }
            }
            if(col[0] == 3){
                xWin = true;
            }
            if(col[1] == 3){
                yWin = true;
            }
        }
        int[] left = new int[2];
        for(int i=0, j=0; i <3 && j < 3; j ++, i++){
            if(board[i][j] == 'X'){
                left[0] ++;
            } else if(board[i][j] == 'O'){
                left[1]++;
            }
        }
        if(left[0] == 3){
            xWin = true;
        }
        if(left[1] ==3){
            yWin = true;
        }
        int[] right = new int[2];
        for(int i=0, j=2; i <3 && j >=0; j --, i++){
            if(board[i][j] == 'X'){
                right[0] ++;
            } else if(board[i][j] == 'O'){
                right[1]++;
            }
        }
        if(right[0] == 3){
            xWin = true;
        }
        if(right[1] ==3){
            yWin = true;
        }
        if(xWin && yWin) return  false;
        if(xWin && count[0] != count[1] + 1) return false;
        if(yWin && count[0] != count[1]) return false;
        return true;
    }

    public static void main(String[] args){
        System.out.println((new ValidTicTacToe()).validTicTacToe(new String[]{"XXO","XOX","OXO"}));
    }

}
